local sk__jiquan = fk.CreateSkill {

  name = "sk__jiquan",

  tags = {},

}



sk__jiquan:addEffect("active", {
  name = "sk__jiquan",
  anim_type = "control",
  prompt = "#sk__jiquan",
  card_num = 0,
  min_target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(sk__jiquan.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, player, to_select, selected, selected_cards)
    if to_select ~= player then
      return not to_select:isNude() or
          #to_select.player_skills > 0
    end
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    room:sortByAction(effect.tos)
    local targets = effect.tos
    local mark = player:getTableMark(sk__jiquan.name)
    for _, id in ipairs(effect.tos) do
      mark[string.format("%.0f", id.id)] = (mark[string.format("%.0f", id.id)] or 0) + 1
    end
    room:setPlayerMark(player, sk__jiquan.name, mark)
    for _, target in ipairs(targets) do
      if player.dead then return end
      if not target.dead then
        local n = mark[string.format("%.0f", target.id)]
        room:setPlayerMark(target, "sk__jiquan-tmp", n)
        local success, dat = room:askForUseActiveSkill(target, "#sk__jiquan_active",
          "#sk__jiquan-choose:" .. player.id .. "::" .. n, true)
        room:setPlayerMark(target, "sk__jiquan-tmp", 0)
        local skill, cards = "", {}
        if not success or (dat and
              ((dat.interaction == "Cancel" and #dat.cards == 0) or
                (dat.interaction ~= "Cancel" and player:hasSkill(dat.interaction, true)))) then
          local skills = table.map(table.filter(target.player_skills, function(s)
            return s:isPlayerSkill(target) and s.visible and not player:hasSkill(s, true)
          end), function(s)
            return s.name
          end)
          if #skills > 0 then
            skill = table.random(skills)
          else
            cards = table.random(target:getCardIds("he"), n)
          end
        elseif dat then
          if #dat.cards > 0 then
            cards = dat.cards
          else
            skill = dat.interaction
          end
        end
        if skill ~= "" then
          room:handleAddLoseSkills(player, skill, nil, true, false)
          room:handleAddLoseSkills(target, "-" .. skill, nil, true, false)
        end
        if #cards > 0 then
          room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonGive, sk__jiquan.name, nil, false, target)
        end
      end
    end
    if player.dead then return end
    local n = 0
    for _, target in ipairs(targets) do
      n = n + target.maxHp
    end
    if player.maxHp <= n then
      room:changeMaxHp(player, 1)
      if not player.dead and player:isWounded() then
        room:recover({
          who = player,
          num = 1,
          recoverBy = player,
          skillName = sk__jiquan.name
        })
      end
    end
  end,
})

return sk__jiquan
